<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
    <div style="display: flex; align-items: center; padding: 1px 15px; position: relative;">
      <!-- 左侧新建按钮 -->
      <el-button class="idoo-details-add">新建</el-button>
      <!-- 右侧信息区域：垂直展示 -->
      <div style="display: flex; flex-direction: column; margin-left: 10px;">
        <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">角色</el-button></span>
        <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
          <span class="sub-title">{{ roleText }}</span>
          <el-tooltip content="保存" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
              <UploadFilled />
            </el-icon>
          </el-tooltip>
          <el-tooltip content="撤销修改" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleRevert">
              <RefreshLeft />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
      <!-- 菜单按钮，固定位置居中 -->
      <div style="position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);">
        <el-button class="idoo-details-button" style="width: 85px;" :icon="Menu">
          <span>菜单<br />{{ menuCouont }}</span>
        </el-button>
      </div>
    </div>
    <!-- 带阴影的分割线 -->
    <div class="divider"></div>
    <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
    <div class="content-section">
      <div style="display: flex; width: 100%;">
        <!-- 左侧：无阴影的Card，占整体宽度的65%，用于表单的详情数据 -->
        <el-card style="box-shadow: none; width: 65%; margin-right: 10px;">
          <el-form :model="roleForm" style="width: 100%;">
            <el-form-item label="" prop="roleName">
              <el-input v-model="roleForm.roleName"
                style="font-size: 30px; height: 60px; line-height: 60px; width: 70%; padding: 10px;"
                class="idoo-details-input" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="24">
                <el-form-item label="角色编码">
                  <el-input v-model="roleForm.roleKey"
                    style="width: 100%; height: 40px; line-height: 60px; width: 70%; padding: 10px;"
                    class="idoo-details-input" placeholder="编码    例如：生产计划专员 可为：SCJHZY"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="数据权限">
                  <el-select v-model="roleForm.dataScope" placeholder="请选择数据权限" style="width: 70%;"
                    class="idoo-details-select">
                    <el-option v-for="item in codeStore().getSystemCode('ROLE_DATA_SCOPE')" :key="item.bizValue"
                      :label="item.bizName" :value="item.bizValue" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-select v-model="roleForm.status" placeholder="请选择状态" style="width: 70%;"
                    class="idoo-details-select">
                    <el-option v-for="item in codeStore().getSystemCode('SYSTEM_TABLE_STATUS')" :key="item.bizValue"
                      :label="item.bizName" :value="item.bizValue" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 20px;">
              <!-- 将标签页移到这里，表单下方 -->
              <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="权限菜单" name="first">
                  <RoleMenuInfos :roleMenuList="roleMenuList" @clickCallBack="permissionMenuCallBack" />
                </el-tab-pane>
                <el-tab-pane label="数据权限" name="second">Config</el-tab-pane>
              </el-tabs>
            </el-row>
          </el-form>
        </el-card>

        <!-- 右侧：修改记录区域，保持背景色 -->
        <div style="width: 35%; padding: 10px;">
          <!-- 修改记录内容 -->
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { UploadFilled, Menu, RefreshLeft } from '@element-plus/icons-vue';
import { _getRoleInoById, _getRoleMenuInfoByRoleId, _saveRoleInfo, _updateRoleInfo } from '@/api/generic/role/role-api';
import router from '@/router';
import { ElMessageBox, type TabsPaneContext } from 'element-plus';
import { codeStore } from '@/stores/codeStore';
import RoleMenuInfos from './roleMenuInfos.vue';
const route = useRoute();
const roleText = ref("");
const isFormChanged = ref(false);
const originalFormData = ref<RoleForm>({});
const activeName = ref('first')
const roleMenuList = ref([]);
const roleMenuLastMenuIds = ref<string[]>([]);


// 比较两个数组的值是否相等（无序）
const arraysEqual = (arr1: any[], arr2: any[]) => {
  return arr1.length === arr2.length && arr1.every(value => arr2.includes(value));
};
const permissionMenuCallBack = (item: object) => {
  console.error(item);
  if (item) {
    const lastArray = JSON.parse(item.last) || [];
    const originalArray = JSON.parse(item.original) || [];
    console.log("子页面菜单回调2：", lastArray);
    console.log("子页面菜单回调1：", originalArray);
    roleMenuLastMenuIds.value = Array.isArray(lastArray) ? lastArray : [];
    isFormChanged.value = !arraysEqual(lastArray, originalArray);
  }
}
const handleBack = () => {
  if (isFormChanged.value) {
    ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await handleSave();
    }).finally(() => {
      router.push({ path: route.fullPath.replace('/add', '') })
    })
  } else {
    router.push({ path: route.fullPath.replace('/add', '') })
  }
}
// 定义表单数据类型
interface RoleForm {
  id?: string;
  roleName?: string;
  roleKey?: string;
  dataScope?: string;
  status?: string;
}

// 初始化表单数据
const roleForm = ref<RoleForm>({
  id: '',
  roleName: '',
  roleKey: '',
  dataScope: '',
  status: '',
});

const resetForm = () => {
  originalFormData.value = JSON.parse(JSON.stringify(roleForm.value));
  roleText.value = roleForm.value.roleName || '新建';
  isFormChanged.value = false;
}
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
const routParams = route.query;

// 监听表单变化
watch(() => roleForm.value, (newVal) => {
  isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
}, { deep: true });

//初始化加载数据
onMounted(async () => {
  //获取用户数据
  if (routParams.id) {
    //如果当前不是通过主界面菜单跳转，不加载第一个菜单路由，指定路由加载
    const res = await _getRoleInoById({ roleId: routParams.id })
    roleForm.value = res;
    originalFormData.value = JSON.parse(JSON.stringify(res));
    roleText.value = roleForm.value.roleName || '';
    const roleMenuRes = await _getRoleMenuInfoByRoleId(routParams.id as string);
    roleMenuList.value = roleMenuRes.data || [];
    console.log("角色菜单数据：", roleMenuRes.data);
  }
  else {
    resetForm();
  }
});

//菜单数量
const menuCouont = ref(0);

// 保存处理函数
const handleSave = async () => {
  // TODO: 实现保存逻辑
  console.log('保存表单数据', roleForm.value);
  console.log(roleMenuLastMenuIds.value);

  // 确保 roleMenuLastMenuIds 是一个数组
  const response = routParams.id
    ? await _updateRoleInfo({ ...roleForm.value, menuIds: roleMenuLastMenuIds.value })
    : await _saveRoleInfo({ ...roleForm.value, menuIds: roleMenuLastMenuIds.value });
  if (response && response.code === 200) {
    resetForm();
  }
};

// 撤销修改，还原表单
const handleRevert = () => {
  roleForm.value = JSON.parse(JSON.stringify(originalFormData.value));
};

</script>
<style scoped>
:deep(.el-input__inner) {
  --el-input-inner-height: none;
}

:deep(.el-card__body) {
  padding: 1% !important;
  justify-content: unset !important;
}

.hover-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hover-icon:hover {
  transform: translateY(-2px);
}

.sub-title {
  font-size: 14px;
  color: #666;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-top: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-section {
  flex: 1;
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs {
  position: relative;
  width: 100%;
}

:deep(.el-tabs__nav-wrap::after) {
  position: absolute;
  content: '';
  width: 100%;
  height: 2px;
  background-color: var(--el-border-color-light);
  bottom: 0;
  left: 0;
  z-index: 1;
}

:deep(.el-tabs__nav.is-top) {
  margin-left: 10px
}

:deep(.el-tabs__header) {
  width: 100%;
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
}
</style>
